from django.shortcuts import render, redirect
from app01 import models
from app01.models import Department, UserInfo, PrettyNum
from app01.utils.form import UserModelForm, PrettyModelForm, PrettyEditModelForm
from app01.utils.pageination_amd_search import Pagination
# Create your views here.

def pretty_list(request):

    # 搜索模块
    data_dict = {}
    search_data = request.GET.get("q", "")
    if search_data:
        data_dict['mobile__contains'] = search_data


    queryset = models.PrettyNum.objects.filter(**data_dict)
    page_object = Pagination(request, queryset=queryset, pege_size=5)


    context = {
            'search_data': search_data,
            'page_queryset': page_object.page_queryset,
            'page_string': page_object.html(),
    }

    return render(request, 'pretty_list.html', context)
def pretty_add(request):
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request,
                      'pretty_add.html',
                      {'form': form})
        # 接收网页提交的数据
    form = PrettyModelForm(data=request.POST)
    # 校验
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request,
                  'pretty_add.html',
                  {'form': form})
def pretty_edit(request, nid):
    row_object = PrettyNum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})

    # modelform接收POST请求数据 根据提交的信息将数据自动填充到输入框中
    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
    return redirect("/pretty/list/")
def pretty_del(request, nid):
    PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")